<template>
  <div>
      <div>
        <p class="fwbold fs-md mg20">· 服务商信息</p>
        <el-divider></el-divider>
      </div>
      <div class="pl40 pr40">
        <el-form :rules="serviceRules" label-width="120px" ref="serviceForm" :model="serviceData" label-position="right"
                size="medium">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="服务商" prop="companyName">
                <el-input placeholder="请输入服务商名称" style="width:100%" v-model="serviceData.companyName" :disabled="disabledFlag"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="companyPhone" label-width="100px">
                <el-input v-model="serviceData.companyPhone" type="phone" placeholder="请输入服务商联系电话"
                          style="width:100%" :disabled="disabledFlag"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="24">
            <el-form-item label="服务商地址" prop="companyAddress">
              <el-input type="text" placeholder="请输入服务商地址" style="width:100%"
                        v-model="serviceData.companyAddress" :disabled="disabledFlag"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工作时间" prop="workDate">
              <div class="row-start">
                <el-checkbox-group v-model="serviceData.workDate" :disabled="disabledFlag">
                  <el-checkbox label="1">周一</el-checkbox>
                  <el-checkbox label="2">周二</el-checkbox>
                  <el-checkbox label="3">周三</el-checkbox>
                  <el-checkbox label="4">周四</el-checkbox>
                  <el-checkbox label="5">周五</el-checkbox>
                  <el-checkbox label="6">周六</el-checkbox>
                  <el-checkbox label="7">周日</el-checkbox>
                </el-checkbox-group>
                <el-time-picker class="time-picker_box" v-model="serviceData.workingHours" is-range range-separator="-"
                                format="HH:mm" value-format="HH:mm"
                                start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"
                                @change="changeWorkTime" :disabled="disabledFlag"/>
              </div>

            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务商LOGO" prop="companyLogo">
              <div class="row-start">
                  <img v-if="serviceData.companyLogo" :src="`/api/public/file/v1/public/get/${serviceData.companyLogo}`" style="height:148px" alt="" @error="setDefaultImage">
                  <uploadImage :class="disabledFlag ? 'disablecss': ''"   @setCardPic="setImageList" :limit="2"/>
              </div>
              <div class="fs14 color-warning"><i class="el-icon-warning" />服务商LOGO只能选择一张图片。</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务商简介" prop="companyIntroduction">
              <div :class="disabledFlag ? 'disablecss': ''">
                  <tiny-editor v-model="serviceData.companyIntroduction"/>
                  <div class="fs14 color-warning"><i class="el-icon-warning" />机构简介上传图片只作公共展示，专家评审以文字为准。</div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="21">
            <el-form-item>
              <div class="submit_box">
                <!-- <el-button type="info" plain @click="onSubmitToSave" style="width: 120px">暂时保存</el-button> -->
                <!-- <el-button type="plain" @click="goBack">返回</el-button> -->
                <!-- <el-button v-if="userInfo.isServiceInfoComplete && disabledFlag==true" plain type="primary" @click="disabledFlag = false">编辑</el-button> -->
                <el-button type="primary" v-if="!disabledFlag" :loading="submitBtnLoading" @click="onSubmitToUpdate">保存</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-form>

      </div>
  </div>
</template>
<script>
// 服务商信息组件
import TinyEditor from "@/components/TinyEditor";
import uploadImage from "@/components/upload/uploadImageCropper.vue";
import {updateCompanyInfo,companyInfoDetail} from "@/api/homeApi";
import { mapGetters } from 'vuex'
export default {
  name: "serviceCompanyComp",
  data() {
    return {
      submitBtnLoading: false,
      formState: 0,
      serviceData: {
        companyName: '',
        companyPhone: '',
        companyAddress: '',
        workDate: [],
        workingHours: ['', ''],
        companyIntroduction: '',
        companyLogo: '',
        editable:false
      },
      serviceRules: {
        companyName: [{required: true, message: '请输入服务商名称', trigger: 'blur'}],
        companyPhone: [{required: true, message: '请输入服务商联系电话', trigger: 'blur'}, {
          pattern: /^((0\d{2,3}-\d{7,8})|(1[3-9]\d{9}))$/,
          message: '请输入正确的手机号码或者座机号',
        }],
        companyAddress: [{required: true, message: '请输入服务商地址', trigger: 'blur'}],
        workDate: [{required: true, message: '请选择工作时间', trigger: 'change'}],
        companyLogo: [{required: true, message: '请上传服务商LOGO', trigger: 'change'}],
        companyIntroduction: [{required: true, message: '请输入服务商简介', trigger: 'blur'}]
      },
       tableList:[],
       uploadFlag: false,
       disabledFlag: false
    }
  },
  components: {
    TinyEditor,
    uploadImage,
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  mounted() {
    this.getCompanyInfoDetail()
  },
  methods: {
    setDefaultImage(event) {
      event.target.src = require('@/assets/image/error.jpg');
    },
    goBack() {
      this.$router.go(-1)
    },
    setImageList(files) {
      this.uploadFlag = true
      console.log('setImageList',files)
      this.$set(this.serviceData, 'companyLogo', files[files.length - 1])
      // 在 DOM 更新完成后执行表单校验
      this.$nextTick(() => {
        this.$refs['serviceForm'].validateField('companyLogo')
      })
    },
    getCompanyInfoDetail() {
      companyInfoDetail().then(res => {
        if (res.code === 200) {
          // 遍历res.data 的属性，有值才会赋值给serviceData里面的元素，使用forEach遍历
          if(!res.data.editable){
              this.disabledFlag = true
          }
          Object.keys(res.data).forEach(key => {
            if (res.data[key]) {
              // 如果key = workBeginTime
              if (key === 'workBeginTime') {
                this.serviceData.workingHours = [res.data.workBeginTime, res.data.workEndTime]
              } else if (key === 'workDate') {
                this.serviceData.workDate = res.data.workDate?.split(',')
              } else {
                this.serviceData[key] = res.data[key];
              }
            }
          });
        }
      })
    },
    onSubmitToUpdate() {
      console.log('this.serviceData',this.serviceData)
      this.$refs['serviceForm'].validate(valid => {
        if (valid) {
          let data = {}
          let submitKey = ['companyAddress', 'companyIntroduction', 'companyLogo', 'companyName', 'companyPhone', 'workDate']
          submitKey.forEach(item => {
            if (this.serviceData.hasOwnProperty(item)) {
              if (item === 'workDate') {
                data[item] = this.serviceData[item].toString()
              } else {
                data[item] = this.serviceData[item]
              }
            }
          })
          if(!this.serviceData.workingHours || (!this.serviceData.workingHours[0] || !this.serviceData.workingHours[1]) ){
              this.$message.error('请选择工作时间')
          } else { 
            data['workBeginTime'] = this.serviceData.workingHours[0]
            data['workEndTime'] = this.serviceData.workingHours[1] 
          }
          this.submitBtnLoading = true
          updateCompanyInfo(data).then(res => {
            if (res.code === 200) {
              if(this.serviceData.editable){
                this.$message.success('修改成功,请前往入驻申请重新提交申请')
              } else {
                this.$message.success('保存成功,请前往入驻申请提交材料')
              }
              this.$store.dispatch('user/getUserInfo')
              this.$router.push({name: '申请入驻平台'})
            }
          }).catch(() => {

          }).finally(() => {
            this.submitBtnLoading = false
          })
        }
      })
    },
    changeWorkTime() {
      this.$set(this.serviceData, 'workBeginTime', this.serviceData.workingHours[0])
      this.$set(this.serviceData, 'workEndTime', this.serviceData.workingHours[1])
    },
    onSubmitToSave() {
    }
  },
}
</script>


<style scoped lang="scss">
@import "@/assets/css/element-variables";
:deep(.el-input.is-disabled .el-input__inner){
  color: #333;
}
:deep(.el-range-editor.is-disabled) {
  color: $text-color;
}
:deep(.el-checkbox) {
  margin-right: 32px !important;
}

:deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: $--color-primary;
  border-color: $--color-primary;
}

:deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: $--color-primary;
}

:deep(.el-form-item) {
  margin-bottom: 34px;
}
.disablecss {
  pointer-events: none;
  opacity: 0.5;
}

.submit_box {
  margin-top: 8px;
  text-align: center;

  button {
    width: 154px !important;

    &:last-child {
      margin-left: 72px;
    }
  }
}

.time-picker_box {
  margin-left: 42px;
}

:deep(.el-button--info.is-plain) {
  color: $text-color;
}
</style>
